<?php

class Db {
	
	const COMMON = "common";
	
	private static $connections = array( "common" => null );
	
	private static $databases = array( "common" => "table_test" ) ;
	
	private static $registered = false ;
	
	public static function init( $db_name ) {
			$dbhost = 'localhost';
			$dbuser = 'root'; // tutaj podajemy login do bazy
			$dbpass = ''; // tutaj podajemy hasło do bazy
			$dbtype = $db_name;
			$dbname = self::$databases[$dbtype];
			
			if( self::$connections[$dbtype] != null ) return ;

			self::$connections[$dbtype] = mysql_connect($dbhost, $dbuser, $dbpass, true) or die ('Nie moge połaczyc sie z Mysql'. mysql_error()); //łaczymy z baza
			mysql_select_db ($dbname, self::$connections[$dbtype] ) or die ('Nie moge wybrać bazy '.$dbtype.' -> '.$dbname); //wybieramy baze danych
			mysql_query("SET NAMES 'utf8'", self::$connections[$dbtype] );
			mysql_query("SET CHARACTER SET utf8", self::$connections[$dbtype] );
			mysql_query("START TRANSACTION", self::$connections[$dbtype] );
			
			if( !self::$registered ){
				 register_shutdown_function( function() { DB::destruct(); } );
				 self::$registered = true;
			}	
	}
	
	
	public static function destruct() {
		foreach( self::$connections as $k => $con ) {	
			if( $con != null ) {
				mysql_query( "ROLLBACK", $con );
						
				if(!mysql_close( $con ))
					die('Invalid mysql_close:' . mysql_error( ).' , conn: '. $con );
				
				self::$connections[$k] = null ;
			}
		}
	}
		
	public static function query( $query, $db = self::COMMON ) {
		//print_r($query.": $db : ".self::$connections[$db]."<br />");
		if( self::$connections[$db] == null ) DB::init($db) ;
		$result = mysql_query( $query, self::$connections[$db] ) ;
		if (!$result) die('Invalid query ('.$db.'): <b>'.$query.'</b><br/> - ' . mysql_error());
		return $result ;
	}
	
	public static function toArray( $query_resource ) {
		$ret = array() ;
		while ($row = mysql_fetch_array($query_resource , MYSQL_ASSOC)) {
				$ret[] = $row ;
		}
		return $ret ;
	}
}

?>